import { Ref, defineComponent, ref } from 'vue';
import { getRawProps, useNamespace } from '@ibiz-template/vue3-util';
import { DynamicTextExtendController } from './controller';
import './dynamic-text-extend.scss';

export const DynamicTextExtend = defineComponent({
  name: 'DynamicTextExtend',
  props: getRawProps<DynamicTextExtendController>(),
  setup(props) {
    const ns = useNamespace('dynamic-text-extend');
    const c = props.controller;
    const _value: Ref<string> = ref('');
    const isEdit: Ref<boolean> = ref(false);
    let oldValue: string = '';

    if (c) {
      _value.value = c.getDataValue();
      oldValue = _value.value;
    }

    const closeEdit = () => {
      isEdit.value = false;
      _value.value = oldValue;
    };

    const handleChange = (value: string) => {
      _value.value = value;
      c.setDataValue(value);
    };

    const handleSave = async () => {
      const result = await c.saveData();
      if (result.ok) {
        isEdit.value = false;
        oldValue = _value.value;
      }
    };

    const handleClick = () => {
      c.onClick();
    };
    return {
      ns,
      _value,
      isEdit,
      closeEdit,
      handleChange,
      handleSave,
      handleClick,
    };
  },
  render() {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
          this.isEdit ? this.ns.m('edit') : '',
        ]}
      >
        {this.isEdit
          ? [
              <el-input
                v-model={this._value}
                onClick={(event: MouseEvent) => {
                  event.stopPropagation();
                }}
                onChange={(value: string) => this.handleChange(value)}
              />,
              <div
                class={this.ns.e('button')}
                onClick={() => this.handleSave()}
              >
                <ion-icon name='checkmark-outline'></ion-icon>
              </div>,
              <div class={this.ns.e('button')} onClick={this.closeEdit}>
                <ion-icon name='close-outline'></ion-icon>
              </div>,
            ]
          : [
              <div class={this.ns.e('text')} onClick={() => this.handleClick()}>
                {this._value}
              </div>,
              <div
                class={this.ns.e('button')}
                onClick={() => {
                  this.isEdit = true;
                }}
              >
                <ion-icon name='pencil-outline'></ion-icon>
              </div>,
            ]}
      </div>
    );
  },
});
